package com.test.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;

import java.util.Arrays;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/11/29 16:13
 * 切面类
 * @Aspect 告诉spring当前类是一个切面类
 * <p>
 * JoinPoint一定要放在参数的第一位
 */
@Slf4j
@Aspect
public class LogAspect {

    /**
     * 抽取公共的切入点表达式
     * 1.本类引用
     * 2.其他的切面类引用
     */
    @Pointcut("execution(public int com.test.aop.MathCalculator.*(..))")
    public void pointCut() {
    }

    //在目标方法之前切入：切入点表达式（指定在哪个方法切入）
    @Before("com.test.aop.LogAspect.pointCut()")
    public void logStart(JoinPoint joinpoint) {
        Signature signature = joinpoint.getSignature();
        String methodName = signature.getName();
        Object[] args = joinpoint.getArgs();
        log.info("除法{}运行...@Before参数是：{}", methodName, Arrays.toString(args));
    }

    @After("pointCut()")
    public void logEnd(JoinPoint joinpoint) {
        Signature signature = joinpoint.getSignature();
        String methodName = signature.getName();
        log.info("除法{}结束。。。@After", methodName);
    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void logReturn(Object result) {
        log.info("除法正常返回@AfterReturning，结果是{}", result);
    }

    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void logException(JoinPoint joinPoint, Exception exception) {
        String methodName = joinPoint.getSignature().getName();
        log.info("除法{}异常，异常信息是{}", methodName, exception.getMessage());
    }
}
